<template>
    <div class="category-management">
        <!-- 分类面板 -->
        <el-card class="mb-4" shadow="hover">
            <template #header>
                <span>分类管理</span>
            </template>
            <div class="category-levels">
                <template v-for="level in 4" :key="level">
                    <div class="level-panel">
                        <div class="level-header">
                            <h3>{{ level }}级分类</h3>
                            <el-button type="primary" size="small" @click="handleAddClick(level)"
                                :disabled="!canAddSubCategory(level)">
                                <el-icon>
                                    <Plus />
                                </el-icon>添加
                            </el-button>
                        </div>
                        <div class="category-list" v-loading="loading" element-loading-text="加载中...">
                            <template v-if="levelCategories[level]?.length">
                                <div v-for="item in levelCategories[level]" @click="handleCategoryClick(item, level)"
                                    :key="item.id" class="category-item" :class="{
                                        'active': selectedCategories[level]?.id === item.id,
                                    }">
                                    <span class="category-name">
                                        {{ item.value }}
                                    </span>
                                    <div class="category-actions">
                                        <el-tooltip content="删除" placement="top">
                                            <el-icon class="action-icon delete" @click.stop="handleDelete(item)">
                                                <Delete />
                                            </el-icon>
                                        </el-tooltip>
                                    </div>
                                </div>
                            </template>
                            <!-- 新增分类的输入框 -->
                            <div v-if="addingLevel === level" class="category-item adding">
                                <el-input ref="inputRef" v-model.trim="newCategoryName" placeholder="请输入分类名称"
                                    size="small" maxlength="50" :validate-event="false" @keyup.enter="handleSubmit"
                                    @blur="handleInputBlur">
                                    <template #append>
                                        <el-button style="margin-right: 1px;" @click="handleSubmit"
                                            :loading="submitting">
                                            确定
                                        </el-button>
                                        <el-button @click="cancelAdd">
                                            取消
                                        </el-button>
                                    </template>
                                </el-input>
                            </div>
                            <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
                                <el-button icon="plus" type="primary" @click="handleAddClick(level)" circle></el-button>
                            </div>
                            <el-empty v-if="!levelCategories[level]?.length" description="暂无数据" />
                        </div>
                    </div>
                </template>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { createCategoryApi, deleteCategoryApi, getCategoryApi } from '@/api/constant'
import { handleError } from '@/utils/handleError'
import { findAllSubCategories } from '@/utils/category'

// 响应式状态
const loading = ref(false)
const submitting = ref(false)
const categories = ref([])
const selectedCategories = ref({}) // 改为对象,按层级存储选中项
const addingLevel = ref(null) // 当前正在添加的层级
const newCategoryName = ref('') // 新分类名称
const inputRef = ref(null) // 输入框引用

// 计算属性：各层级显示的分类
const levelCategories = computed(() => {
    const result = {}
    // 第一级始终显示所有一级分类
    result[1] = categories.value
        .filter(item => item.level === 1)
        .sort((a, b) => a.sort - b.sort)

    // 根据选中项显示下级分类
    for (let level = 2; level <= 4; level++) {
        const parentCategory = selectedCategories.value[level - 1]
        if (parentCategory) {
            result[level] = categories.value
                .filter(item => item.part_of === parentCategory.id)
                .sort((a, b) => a.sort - b.sort)
        } else {
            result[level] = []
        }
    }

    return result
})

// 判断是否可以添加子分类
const canAddSubCategory = (level) => {
    if (level === 1) return true
    return selectedCategories.value[level - 1] !== undefined
}

// 处理分类点击
const handleCategoryClick = (category, level) => {
    if (selectedCategories.value[level]?.id === category.id) {
        // 如果点击已选中的分类,则取消选中
        selectedCategories.value[level] = null
        // 清除下级选中状态
        for (let i = level + 1; i <= 4; i++) {
            selectedCategories.value[i] = null
        }
    } else {
        // 选中新的分类
        selectedCategories.value[level] = category
        // 清除下级选中状态
        for (let i = level + 1; i <= 4; i++) {
            selectedCategories.value[i] = null
        }
    }
}

// 处理添加按钮点击
const handleAddClick = (level) => {
    addingLevel.value = level
    newCategoryName.value = ''
    nextTick(() => {
        inputRef.value[0].focus()
    })
}

// 取消添加
const cancelAdd = () => {
    addingLevel.value = null
    newCategoryName.value = ''
}

// 处理输入框失焦
const handleInputBlur = () => {
    // 如果输入框为空，则取消添加
    if (!newCategoryName.value) {
        cancelAdd()
    }
}

const handleDelete = async (category) => {
    try {
        // 找出所有受影响的分类
        const affectedCategories = findAllSubCategories(category);
        const totalCount = affectedCategories.length;

        // 更新确认框的提示信息
        const message = totalCount > 1
            ? `确认删除分类"${category.value}"及其${totalCount - 1}个子分类吗？删除后将无法恢复！`
            : `确认删除分类"${category.value}"吗？删除后将无法恢复！`;

        await ElMessageBox.confirm(
            message,
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true
            }
        )

        // 删除所有受影响的分类
        await Promise.all(
            affectedCategories.map(cat =>
                deleteCategoryApi({ id: '' + cat.id })
            )
        );

        ElMessage.success('删除成功');
        await fetchAllCategories();

        // 清除受影响层级的选中状态
        const level = category.level;
        for (let i = level; i <= 4; i++) {
            selectedCategories.value[i] = null;
        }
    } catch (error) {
        if (error !== 'cancel') {
            handleError(error, '删除失败', true);
        }
    }
}


// 获取所有级别的分类数据
const fetchAllCategories = async () => {
    loading.value = true
    try {
        const [level1, level2, level3, level4] = await Promise.all([
            getCategoryApi({ level: 1 }),
            getCategoryApi({ level: 2 }),
            getCategoryApi({ level: 3 }),
            getCategoryApi({ level: 4 })
        ])
        categories.value = [...level1.data, ...level2.data, ...level3.data, ...level4.data]
    } catch (error) {
        handleError(error, '获取分类数据失败', true)
    } finally {
        loading.value = false
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!newCategoryName.value) {
        ElMessage.warning('请输入分类名称')
        return
    }
    if (newCategoryName.value.length < 2 || newCategoryName.value.length > 50) {
        ElMessage.warning('分类名称长度应在 2 到 50 个字符之间')
        return
    }

    try {
        submitting.value = true
        const formData = {
            value: newCategoryName.value,
            part_of: addingLevel.value === 1 ? null : selectedCategories.value[addingLevel.value - 1]?.id,
            sort: 0,
            level: addingLevel.value
        }

        await createCategoryApi(formData)
        ElMessage.success('添加成功')

        cancelAdd()
        await fetchAllCategories()
    } catch (error) {
        handleError(error, '添加失败', true)
    } finally {
        submitting.value = false
    }
}

// 初始化
onMounted(() => {
    fetchAllCategories()
})
</script>

<style scoped>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.header h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
}

.category-levels {
    display: flex;
    height: 400px;
    gap: 20px;
}

.level-panel {
    flex: 1;
    min-width: 200px;
    overflow: auto;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: var(--el-border-radius-base);
    background-color: var(--el-bg-color);
    transition: all 0.3s ease;
}

.level-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    background-color: var(--el-bg-color-page);
}

.level-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: var(--el-text-color-primary);
}

.category-list {
    padding: 12px;
    min-height: 300px;
    max-height: 500px;
    overflow-y: auto;
}

.category-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    margin-bottom: 8px;
    border-radius: var(--el-border-radius-base);
    background-color: var(--el-bg-color-page);
    cursor: pointer;
    transition: all 0.2s ease;
}

.category-item.adding {
    cursor: default;
    padding: 4px 8px;
}



.category-item.active {
    background-color: var(--el-color-primary-light-9);
}

.category-name {
    flex: 1;
    margin: 0 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.category-actions {
    display: flex;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.category-item:hover .category-actions {
    opacity: 1;
}

.action-icon {
    font-size: 16px;
    color: var(--el-text-color-secondary);
    cursor: pointer;
    transition: all 0.2s ease;
}

.action-icon:hover {
    color: var(--el-color-primary);
    transform: scale(1.1);
}

.action-icon.delete:hover {
    color: var(--el-color-danger);
}

:deep(.el-checkbox__label) {
    display: none;
}

.category-item.adding :deep(.el-input-group__append) {
    display: flex;
    gap: 8px;
}
</style>